import Taro from '@tarojs/taro';
import {View, Image, Text, ScrollView, SwiperItem, Swiper} from '@tarojs/components'
import React, { Component, ComponentClass } from 'react';
import {AtRate, AtRange, AtIcon, AtDivider} from 'taro-ui'
import {ShopList} from '../../utils/server.interface'
import {RESOURCE_URL, SHOP_APP_CAROUSEL, SHOP_APP_SITERECOMMEND} from '../../constants/api'
import {clearSearch as clearSearchFunc, vcmonitor} from "../../utils/tools";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import {http} from "../../utils/http";
import {newHttp} from "../../utils/request";
import './index.scss'

type PageState = {
  loadMoreStatus: 'more' | 'noMore' | 'loading'
  list: ShopList[]
  size: number
  labelIndex: number
  labelKey: number
  searchName: any
  currentIndex: any
  groupList: any
  label: string
  drawerShow: boolean
  littleMoney: number
  bigMoney: number
  starCount: any
  kmCount: any
  text: string
  carouselImgList: any
  recommend: any
}

class Index extends Component {

  state: PageState = {
    loadMoreStatus: 'loading',
    list: [],
    size: 10,
    labelIndex: 0,
    labelKey: 0,
    searchName: '',
    currentIndex: 0,
    groupList: [],
    label: '',
    drawerShow: false,
    littleMoney: 0,
    bigMoney: 200,
    starCount: '',
    kmCount: '',
    text: '',
    carouselImgList: [],
    recommend: [],
  }

  async UNSAFE_componentWillMount() {
    vcmonitor(this);
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    this.getList()
    if (Taro.getCurrentInstance().router.params.uuid) {
      const res = await newHttp.catchPost(SHOP_APP_CAROUSEL, {uuid: Taro.getCurrentInstance().router.params.uuid || ''})
      const recommend = await newHttp.catchGet(SHOP_APP_SITERECOMMEND, {uuid: Taro.getCurrentInstance().router.params.uuid || ''})
      let carouselImgList = []
      if (res && res.banner_imgs) {
        if (res.banner_imgs.indexOf(',') > 0) {
          carouselImgList = res.banner_imgs.split(',')
        } else {
          carouselImgList = [res.banner_imgs]
        }
      } else {
        carouselImgList = []
      }
      this.setState({carouselImgList, recommend})
    }
  }

  async getList() {
    this.page = 1
    const list = await this.getGoods()
    this.setState({list})
  }

  page = 1

  async onReachBottom() {
    if (this.state.loadMoreStatus != 'noMore') {
      this.setState({loadMoreStatus: 'loading'})
      const old = this.state.list
      this.page++
      const newData = await this.getGoods()
      this.setState({list: [...old, ...newData]})
    }
  }

  jumpedit(uuid) {
    Taro.navigateTo({
      url: '/other/shop/info?uuid=' + uuid
    })
  }

  onOff(gid = 0, num?, title?, price?, stock?, img?) {
    if (gid) {
      const {list, labelIndex, labelKey} = this.state
      list[labelIndex].goods.map((item, index) => {
        if (index != labelKey) {
          if (item.gid == gid) {
            item.img = img
            item.num += num
            item.title = title
            item.price = price
            item.stock = stock
            list[labelIndex].goods.splice(labelKey, 1)
          }
        } else {
          item.img = img
          item.num = num
          item.title = title
          item.price = price
          item.stock = stock
        }
      })
      this.setState({list})
    }
  }

  back() {
    Taro.switchTab({url: '/pages/index/index'})
  }

  async getGoods() {
    Taro.showLoading({title: '加载中...'});
    const params = {
      page: this.page,
      size: this.state.size,
      label: this.state.label,
      littleMoney: this.state.littleMoney,
      bigMoney: this.state.bigMoney,
      starCount: this.state.starCount,
      kmCount: this.state.kmCount,
      searchName: this.state.searchName,
      money: 200, // 根据范围条的长度来的
      uuid: Taro.getCurrentInstance().router.params.uuid || ''
    }
    const goodsData = await http.MPost('/msvc-shop/v1/application/shop/app/shop/page', params)
    if (goodsData) {
      Taro.hideLoading()
    }
    const groupList = goodsData.data.labelArray
    groupList.unshift('全部')
    this.setState({groupList})
    if (goodsData.data.data) {
      if (goodsData.currentPage < goodsData.totalPages) {
        this.setState({loadMoreStatus: 'more'})
      } else {
        this.setState({loadMoreStatus: 'noMore'})
      }
      return goodsData.data.data
    } else {
      this.setState({loadMoreStatus: 'noMore'})
      return []
    }
  }

  searchConfirm() {
    this.page = 1
    this.getList()
  }

  input(value) {
    if (value) {
      this.setState({searchName: value})
    } else {
      clearSearchFunc();
    }
  }

  async clearSearch() {
    await this.setState({searchName: ''}, () => {
      this.getList()
    })
  }

  categoryListClick(currentIndex) {
    try {
      if (this.state.currentIndex === currentIndex) {
        return false
      }
      Taro.showLoading({title: '加载中...'});
      this.page = 1
      this.setState({
        currentIndex,
        loadMoreStatus: 'loading',
        label: currentIndex == 0 ? '' : this.state.groupList[currentIndex]
      }, async () => {
        this.getList()
        Taro.hideLoading()
      })
    } catch (e) {
      Taro.hideLoading()
    }
  }

  handleChange(value) {
    const littleMoney = value[0]
    const bigMoney = value[1]
    let text = ''
    if (value[0] == 0 && value[1] == 0) {
      text = '￥10 以下'
    } else if (value[1] == 200) {
      text = `￥${value[0]} 以上`
    } else {
      text = `￥${value[0]} ~ ￥${value[1]}`
    }
    this.setState({
      littleMoney: littleMoney,
      bigMoney: bigMoney,
      text: text
    })
  }

  search() {
    this.page = 1
    this.setState({drawerShow: false})
    this.getList()
  }

  async reset() {
    this.page = 1
    this.setState({
      label: '',
      littleMoney: 0,
      bigMoney: 200,
      starCount: '',
      kmCount: '',
      text: ''
    }, async () => {
      await this.getList();
    })

  }

  render() {
    const {
      littleMoney,
      bigMoney,
      kmCount,
      starCount,
      text,
      drawerShow,
      groupList,
      currentIndex,
      searchName,
      loadMoreStatus, list,
      carouselImgList,
      recommend
    } = this.state
    return (
      <View className='shopcar-root regional-category-shop'>
        <GzhAuth />
        {/*<View className='search-top'>
          <AtSearchBar onConfirm={this.searchConfirm.bind(this)} showActionButton={false}
            onClear={this.clearSearch.bind(this)} onActionClick={this.searchConfirm.bind(this)}
            value={searchName} onChange={this.input.bind(this)} placeholder='输入店铺名称搜索'
          />
        </View>*/}
        {drawerShow && <View className='search'>
          <View className='search-price'>
            <View style='display: block;'>
              <Text className='search-price-title'>人均价筛选</Text>
              <Text className='search-word-text'>{text}</Text>
            </View>
            <View className='search-word'>
              <Text>￥0</Text>
              <Text>￥200+</Text>
            </View>
            <AtRange
              blockSize={16}
              value={[littleMoney || 0, bigMoney || 200]}
              min={0}
              max={200}
              onChange={this.handleChange.bind(this)}
            />
          </View>
          <View className='search-distance'>
            <View className='search-tip'>
              <Text className={`tips ${kmCount == 2 ? 'active' : ''}`} onClick={() => {
                this.setState({kmCount: 2})
              }}
              >2km内</Text>
              <Text className={`tips ${kmCount == 4 ? 'active' : ''}`} onClick={() => {
                this.setState({kmCount: 4})
              }}
              >4km内</Text>
              <Text className={`tips ${kmCount == 6 ? 'active' : ''}`} onClick={() => {
                this.setState({kmCount: 6})
              }}
              >6km内</Text>
              <Text className={`tips ${kmCount == 8 ? 'active' : ''}`} onClick={() => {
                this.setState({kmCount: 8})
              }}
              >8km内</Text>
            </View>
          </View>
          <View className='search-brand'>
            <Text className='search-brand-title'>品质</Text>
            <View className='search-tip'>
              <Text className={`tips ${starCount == 5 ? 'active' : ''}`} onClick={() => {
                this.setState({starCount: 5})
              }}
              >5星好评</Text>
              <Text className={`tips ${starCount == 4 ? 'active' : ''}`} onClick={() => {
                this.setState({starCount: 4})
              }}
              >4星以上</Text>
              <Text className={`tips ${starCount == 3 ? 'active' : ''}`} onClick={() => {
                this.setState({starCount: 3})
              }}
              >3星以上</Text>
            </View>
          </View>
          <View className='search-btn'>
            <View className='search-btn-reset' onClick={this.reset.bind(this)}>重置</View>
            <View className='search-btn-comp' onClick={this.search.bind(this)}>完成</View>
          </View>
        </View>}

        {/*轮播图*/}
        {carouselImgList && carouselImgList.length > 0 && <Swiper
          indicatorDots
          autoplay
          indicatorActiveColor={`${process.env.mainColor}`}
          indicatorColor='rgba(255,255,255,0.68)' interval={5000} duration={1000}
          className='swiper'
        >
          {carouselImgList.map((item, index) => <SwiperItem key={index}>
            <Image className='imageFix' src={item} mode='aspectFill' style='width:100%' />
          </SwiperItem>)}
        </Swiper>}

        {/*商家推荐*/}
        {recommend && recommend.length > 0 && <View className='shop-recommend'>
          <View className='shop-recommend-head'>
            <View className='shop-recommend-box'></View>
            <Text className='shop-recommend-title'>商家推荐</Text>
          </View>
          <View className='shop-recommend-shop'>
            {recommend && recommend.length > 0 &&
            <ScrollView scrollWithAnimation enable-flex scrollX className='scroll-view-shop'
                        style='padding-bottom: 0 !important;'
            >
              <View className='regional-category-nav'>
                {
                  recommend.map((item, index) => (
                    <View className='regional-category-nav-item' key={index}
                          onClick={this.jumpedit.bind(this, item.uuid)}
                    >
                      <View
                        className={`regional-category-nav-item-name `}
                      >
                        <View className='shop-recommend-item'>
                          <View className='shop-recommend-item-image'>
                            <Image className='shop-recommend-item-image-image' mode='aspectFill' src={RESOURCE_URL + item.logo}></Image>
                            <View className='shop-recommend-item-image-top'>TOP{index+1}</View>
                          </View>
                          <View className='shop-recommend-item-content'>
                            <View className='shop-recommend-item-content-name'>{item.name}</View>
                            {!!item.business_hours_intro &&<View className='shop-recommend-item-content-time'>营业时间：{item.business_hours_intro || ''}</View>}
                            <View className='shop-recommend-item-content-star'>
                              评分：
                              {!!item.star && item.star > 0 ? <View className='star'>
                                <AtRate className={`star-rate ${process.env.TARO_ENV != "h5" ? 'star-rate-weapp' : ''}`}
                                        value={item.star} size={10}
                                />
                              </View> : '暂无评分'}
                            </View>
                            {!item.business_hours_intro &&<View className='shop-recommend-item-content-time stay-height'>营业时间：</View>}
                          </View>
                        </View>
                      </View>
                    </View>
                  ))
                }
              </View>
            </ScrollView>
            }
          </View>
        </View>}

        <View className='head'>
          {groupList && groupList.length > 0 &&
          <ScrollView scrollWithAnimation enable-flex scrollX className='scroll-view-shop'
            style='padding-bottom: 0 !important;'
          >
            <View className='regional-category-nav'>
              {
                groupList.map((item, index) => (
                  <View className='regional-category-nav-item' key={index}
                    onClick={this.categoryListClick.bind(this, index)}
                  >
                    <View
                      className={`regional-category-nav-item-name ${currentIndex === index ? 'active' : ''}`}
                    >{item}</View>
                  </View>
                ))
              }
            </View>
          </ScrollView>
          }
          <AtIcon size='18' value='icon icon-shaixuan-01' className={`iconClass ${drawerShow ? 'active' : ''}`}
            onClick={
                    () => {
                      this.setState({
                        drawerShow: !drawerShow
                      })
                    }
                  }
          />
        </View>
        <View className='shopCarBox'>
          {list && list.length > 0 && list.map((item: any) =>
            <View className='shopCarlist' key={item.id} onClick={this.jumpedit.bind(this, item.uuid)}>
              <View className='shopCarlist-box'>
                <View className='good-item-dome'>
                  <View className='good-item' hoverClass='none'>
                    <View className='good-item-box'>
                      <View className='img-box'>
                        {!!item.logo && <Image lazyLoad={process.env.TARO_ENV != "h5"}
                          src={RESOURCE_URL + item.logo}
                          mode='aspectFill' className='img'
                        />}{!item.logo && <Image lazyLoad={process.env.TARO_ENV != "h5"}
                          src='https://resource.ivcheng.com/upload/2022/08/26/3d7e1b390cea425ca8a0d8f37c993d01.png'
                          mode='aspectFill' className='img-not'
                        />}
                      </View>
                      <View className='title-box'>
                        <View>
                          <View className='title'>{item.name}</View>
                        </View>
                        <View className='box-middle'>
                          {item.application_open_comment == 1 && <View className='star'>
                            {!!item.star && item.star > 0 &&
                            <AtRate className={`star-rate ${process.env.TARO_ENV != "h5" ? 'star-rate-weapp' : ''}`}
                              value={item.star} size={12}
                            />}
                            <Text
                              className='star-scores'
                            >{!!item.star && item.star > 0 ? Number(item.star).toFixed(1) : '暂无评分'}</Text>
                          </View>}
                          {item.distance && <View className='distance'>
                            <AtIcon value='map-pin' size='14' />
                            {item.distance}
                          </View>}
                        </View>
                        {!!item.consumption_per_person && item.consumption_per_person > 0 && <View className='capita'>
                          人均￥{item.consumption_per_person}
                        </View>}
                      </View>
                    </View>
                  </View>
                </View>
              </View>
              <AtDivider className='shopCarlist-line'></AtDivider>
            </View>)}
          {(list.length == 0) && loadMoreStatus != 'loading' && <View className='shop-list-null'>
            <Image src={`${RESOURCE_URL}/resources/images/carnull.png`} mode='widthFix' />
          </View>}
        </View>
        {drawerShow && <View className='shopCarBox-mask' onClick={() => {
          this.setState({drawerShow: false})
        }}
        />}
        <View style='height: 10px' />
      </View>
    )
  }
}

export default Index as ComponentClass


